<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class generate_model extends CI_Model
{
    private $modelsDir = '';
    public function generate_model()
    {
        parent::__construct();
        $this->modelsDir = $_SERVER['DOCUMENT_ROOT'].'/application/modules/generate/scripts/BO/m_'.$_SESSION['gene']['table'];
        if (!is_dir($this->modelsDir)) mkdir($this->modelsDir, 0777);
    }
    
    /**
 * Form (Header) search by title 
 */    
    private function form_find($table)
    {
        $str = '
    private function formFind()
    {
        $this->load->helper("form");
        $attributes = array("name" => "frmFind", "id" => "frmFind");
        $f = form_open(site_url("'.$table.'/find"), $attributes);
        $data = array("name" => "txt_find", "id" => "txt_find", "value" => "", "style" => "width:200px");
        $f .= form_input($data);
        $s = array("name" => "submit", "value" => t("Find"), "class" => "ibutton green", "style" => "margin-left:10px");
        $f .= form_submit($s);
        if ($this->session->userdata("'.iprefix.'_find_'.$table.'")) {
            $r = array("name" => "btnReset", "value" => "Reset", "class" => "ibutton red", "style" => "margin-left:10px");
            $f .= form_submit($r);
        } 
        $f .= form_close();
        return $f;
    }
    ';
        return str_replace('"', "'", $str);
    }
   
/**
 *  Form (Header) filter
 */    
    
    private function form_Filter($strForenKey, $table)
    {   
        //pages_type pid;article idel
        $str = '';
        $filter = '';
        $filter_post = '';
        $arrKey = explode(';', $strForenKey);
        
        foreach ($arrKey as $val) {
            $val = trim($val);
             $last = strrchr($val, ' '); // last
             $last = trim($last);
             $fist = substr($val, 0, strpos($val, ' ')); // fist
             $fist = trim($fist);
            
        $str .= '
    private function Filter_'.$fist.'()
    {
        $this->load->helper("form");
        $query = $this->db->get("'.$fist.'");
        foreach ($query->result() as $row) {
            $options[$row->id] = $row->title;
        }
        $id = !$this->session->userdata("'.iprefix.'_filter_'.$fist.'") ? 0 : $this->session->userdata("'.iprefix.'_filter_'.$fist.'");
        $attributes = array("name" => "frmFilter'.$fist.'", "id" => "frmFilter'.$fist.'");
        $f = form_open(site_url("'.$table.'/filter'.$fist.'"), $attributes);
        $f .= form_dropdown("'.$last.'", $options, $id);
        $data = array("name" => "btnFilter'.$fist.'", "class" => "ibutton green", "style" => "margin-left:10px", "value" => t("Filter"));
        $f .= form_submit($data);
        if ($this->session->userdata("'.iprefix.'_filter_'.$fist.'")) {
            $r = array("name" => "btnReset", "class" => "ibutton red", "style" => "margin-left:10px", "value" => "Reset");  
            $f .= form_submit($r); 
        }
        $f .= form_close();
        return $f;
    }
    ';
        $filter .= '"fil_'.$fist.'" => '.'$this->Filter_'.$fist.'(), ';
        $filter_post .=' 
        if ($this->session->userdata("'.iprefix.'_filter_'.$fist.'"))
            $this->db->where("'.$table.'.'.$last.'", $this->session->userdata("'.iprefix.'_filter_'.$fist.'"));';

    }
        $str =$this->chuanhoa($str);
        $filter = $this->chuanhoa($filter);
        $filter = substr($filter, 0, strlen($filter) - 2 );
        return array($str, $filter, $filter_post);
    }
    
    private function filter($table, $alias) // cbo
    {
    return '    
    private function cbo_'.$table.'($id = 0)
    {
        $this->load->helper("form");
        $query = $this->db->get("'.$table.'");
        foreach ($query->result() as $row) {
            $options[$row->id] = $row->title;
        }
        $sl = $id == 0 ? set_value("'.$alias.'") : $id;
        return form_dropdown("'.$alias.'", $options, $sl);
    }
    ';
    }
    private function total($table)
    {
        return '
    private function _total()
    {
        return $this->db->count_all_results("'.$table.'"); 
    }
    ';
    }
    public function chk_primaryKey()
    {
        if ($_SESSION['gene']['pk'][0] == '') return '';
        $str = '';
        $arrKey = $_SESSION['gene']['pk'];
        foreach ($arrKey as $val) {
            $val = trim($val);
             $last = strrchr($val, ' '); // last
             $last = trim($last);
             $fist = substr($val, 0, strpos($val, ' ')); // fist
             $fist = trim($fist);
        $str .= '
    public function chk_'.$fist.'_'.$last.'($id)
    {
        $query = $this->db->get_where("'.$fist.'", array("'.$last.'" => $id));
        if ($query->num_rows() > 0) return true;
        return false;
    }
    ';
        }
        return $str;
    }
    
    private function checkById($table)
    {
        return '
    private function _check'.$table.'ById($id)
    {
        $query = $this->db->get_where("'.$table.'", array("id" => $id));
        if ($query->num_rows() > 0) return true;
        else {
            notify_set_messages(notify_atten(t("Record không tồn tại")));
            return false;
        }
    }
    ';
    }
    private function checkForm_rules($str)
    {
        switch ($str) {
           case 'int': return '|integer';
           default: return '';
        }
    }
    private function checkForm()
    {
        $str = '';
        $fieldsDt = $this->db->field_data($_SESSION['gene']['table']);
        $str = '
    public function checkForm()
    {';
    foreach ($fieldsDt as $field) {
        if (in_array($field->name, $_SESSION['gene']['keyAction'])) {
            if ($field == 'id') continue;
        $str .= '
        $this->form_validation->set_rules("'.$field->name.'", t("'.$field->name.'"),"trim|required'.$this->checkForm_rules($field->type).'");';
        }
    }    
    $str .= '
        return $this->form_validation->run();
    } 
    ';
    
        return $this->chuanhoa($str);
    }
    public function dataEdit($table)
    {   
        $str = '';
    $str .= '
    
    public function dataEdit($id)
    {
        if (!$this->_check'.$table.'ById($id)) return redirect(site_url("'.$table.'"));';
        if (in_array('editor', $_SESSION['gene']['arrAction'])) {
            $str .= '
        $this->load->helper("editor");';
        }
        $str .= '
        $query = $this->db->get_where("'.$table.'",array("id" => $id));';
        if ($_SESSION['gene']['fk'] != '') {
            $str .= '
        return array("query" => $query,'; 
            $arrKey = explode(';', $_SESSION['gene']['fk']);
            foreach ($arrKey as $val) {
                $val = trim($val);
                $fist = substr($val, 0, strpos($val, ' ')); // fist
                $fist = trim($fist);
                $last = strrchr($val, ' '); // last
                $last = trim($last);
                $str .= '
                    "cbo_'.$fist.'" => $this->cbo_'.$fist.'($query->row("'.$last.'")), ';
            }    
            $str = substr($str, 0, strlen($str) - 2);
        } 
        else
            $str .= '
        return array("query" => $query'; 
        $str .='
                    );
    }
    ';
    
    $str .= '
    public function dataAdd()
    {';
        if (in_array('editor', $_SESSION['gene']['arrAction'])) {
            $str .= '
        $this->load->helper("editor");';
        }
        if ($_SESSION['gene']['fk'] != '') {
        $str .= '
        return array('; 
            foreach ($arrKey as $val) {
                $val = trim($val);
                $fist = substr($val, 0, strpos($val, ' ')); // fist
                $fist = trim($fist);
                $str .= '"cbo_'.$fist.'" => $this->cbo_'.$fist.'(), ';
            }     
            $str = substr($str, 0, strlen($str) - 2); 
        $str .=');';
        }
        
    $str .= '
    }
    ';
        return $this->chuanhoa($str);
    }
    public function idel($table)
    {
        $flag = false;
        $fields = $this->db->list_fields($table);
        foreach ($fields as $f) {
            if ($f == 'idel') $flag = true;
        }    
        if ($flag) {
            return $this->chuanhoa('
    public function iDel($id)
    {
        $query = $this->db->get_where("'.$table.'", array("id" => $id, "idel" => "Yes"));
        if($query->num_rows() > 0) return true;
        return false;
    }
    ');
        }
    }
    
    private function chuanhoa($str)
    {
        return str_replace('"', "'", $str);
    }
    function cokhoangoai($table, $khoangoai)
    {
        $join = '';
        $filter = '';
        $total = '';
        $str = ' '.$_SESSION['gene']['strDis'];
        $str = str_replace(' ', ' '.$table.'.', $str);
        $khoangoai = explode(';', $khoangoai);
        foreach ($khoangoai as $val) {
            $val = trim($val);
            $ar = explode(' ',$val);
            $alias = $ar[1];
            $str = str_replace($table.'.'.$alias, $ar[0].".title as $alias"."_type", $str);
            $join .= '
        $this->db->join("'.$ar[0].'", "'.$table.'.'.$ar[1].' = '.$ar[0].'.id");';
        $filter .= $this->filter($ar[0], $alias);
        $total .= $this->total($ar[0]);
        }
        return array(trim($str), $join, $filter, $total);
    }
    public function doUpdate()
    {
        $table = $_SESSION['gene']['table'];
        $arrField = $_SESSION['gene']['keyAction'];
    $str = '
    public function doUpdate()
    {
        $this->load->helper("text");
        ';
    foreach ($arrField as $key => $val) {
        $val = trim($val);
        if ($val == '' || $val == 'id') continue;
    $str .= '$this->set'.ucfirst($val).'($this->input->post("'.$val.'"));
        ';
    //$str .= '$field["'.$val.'"] = $this->input->post("'.$val.'");
    //    ';
    }     
   
       
    $str .= '    
        if (isset($_POST["idx"])) {
            $id = decrypt($_POST["idx"]);
            $this->setId($id);
            $this->setChanged(time());
        }
        else {
            $this->setCreated(time());
        }
        return $this->save();
    }
    ';
    return $this->chuanhoa($str);
    }

    public function main()
    {
        $table = $_SESSION['gene']['table'];
             
$str = '<?php if ( ! defined("BASEPATH")) exit("No direct script access allowed");
class '.$table.'_model extends CI_Model
{';
/*
foreach ($_SESSION['gene']['keyAction'] as $field) {
$str .= '
    var $'.$field.' = "";';    
} */   
$str .= '  
    public function __construct()
    {
      parent::__construct();
    }
    
    public function dataSort($field, $order)
    {
      $xOrder =  $order == "asc" ? "desc" : "asc";
      $img = $order == "desc" ? \'<img src=\"/data/admin/down.jpg\" />\' : \' <img src=\"/data/admin/up.jpg\" />\';  
      $url = anchor("'.$table.'/sort/".$field."/".$xOrder, t($field).$img);
      $_SESSION["sm_sort_'.$table.'"] = array("field" => $field, "order" => $order, "url" => $url);
    }
    
    public function dataIndex($target)
    {
      $numshow = 25;';
      if ($_SESSION['gene']['fk'] == '') // neu ko co khoa ngoai
      {
          $strShow = $_SESSION['gene']['strDis'];
          $str .= 
          '
      $this->db->select("'.$strShow.'");
      $this->db->from("'.$table.'");'; 
      }
      else // co khoa ngoai
      {
          $filter = $this->form_Filter($_SESSION['gene']['fk'], $table); // filter
          $arr = $this->cokhoangoai($table, $_SESSION['gene']['fk']);
          $str .= 
          '
      $this->db->select("'.$arr[0].'");
      $this->db->from("'.$table.'");
      '.$arr[1].'
      '.$filter[2];
    
          
      }
            
      $str .= '
      if ($this->session->userdata("'.iprefix.'_find_'.$table.'")) {
        $this->db->like("'.$table.'.title", $this->session->userdata("'.iprefix.'_find_'.$table.'"));
      }
      if (isset($_SESSION["sm_sort_'.$table.'"])) {
        $sort = $_SESSION["sm_sort_'.$table.'"];
        $this->db->order_by("'.$table.'.".$sort["field"], $sort["order"]);
       }
      else {  
        $this->db->order_by("'.$table.'.created", "desc");
      }
      $this->db->limit($numshow, $target);
      $query = $this->db->get();
      $paging = $this->home_model->paging_Admin("'.$table.'/index", $this->_total(), $numshow, 4);
      return array("query"=>$query, "paging"=>$paging,';
      if ($_SESSION['gene']['fk'] != '')
          $str .= $filter[1].","; 
      $str .= '                    
                  "formFind" => $this->formFind());
    }
      ';
      $str = str_replace('"', "'", $str);

      if ($_SESSION['gene']['fk'] != '') $str .= $arr[2];
      $str .= $this->total($table);  
      $str .= $this->checkById($table); 
      $str .= $this->chk_primaryKey(); 
      $str .= $this->form_find($table);  
      if ($_SESSION['gene']['fk'] != '') {
          $str .=  $filter[0]; 
      }
      $str .= $this->dataEdit($table); // dataAdd and dataEdit
      $str .= $this->checkForm(); 
      $str .= $this->idel($table);
      $str .= $this->doUpdate();
        
        $dir = $this->modelsDir.'/'.$table.'_model.php';
$str .= '
}
';
        if (file_exists($dir)) delete_files($dir);
        write_file($dir, $str, 'w');
    }
    
}
